package com.alibaba.org.service.impl;

import com.alibaba.basic.query.BaseQuery;
import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.basic.uitl.MD5Utils;
import com.alibaba.basic.uitl.PageList;
import com.alibaba.basic.uitl.StrUtils;
import com.alibaba.org.domain.Employee;
import com.alibaba.org.mapper.EmployeeMapper;
import com.alibaba.org.service.EmployeeService;
import com.alibaba.system.mapper.RoleMapper;
import com.alibaba.system.vo.EmpAndRoleVo;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.mapper.LogininfoMapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RoleMapper roleMapper;


    /**
     * 查询店铺下的 员工
     *
     * @param shopId
     * @return
     */
    @Override
    public List<Employee> findListByShopId(Long shopId) {
       List<Employee> colleect =  employeeMapper.findAll().stream()
                .filter(emp -> Objects.nonNull(emp) && shopId.equals(emp.getShopId()))
                .collect(Collectors.toList());
        return colleect;

    }
    @Override
    public void add(Employee emp) {
        // todo 下面都是为了数据权限实现
        //  密码
        String salt = StrUtils.getComplexRandomString(32);
        emp.setSalt(salt);
        emp.setPassword(MD5Utils.encrypByMd5(salt + "1"));
        // 添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(emp, logininfo);
        logininfo.setDisable(true);
        logininfo.setType(0);
        logininfoMapper.add(logininfo);
        // todo 添加emp的时候 需要判断一下 是否有店铺id
//        Shop shop = LoginContext.getUserInfo().getShop();
//        if (null != shop){
//            // todo 当前操作人是店铺的人 那么添加的人应该也是店铺的人 那么给个店长的默认角色 其他角色一概不给
//            emp.setShopId(shop.getId());
//            super.add(emp);
//            List<Role> roleList = roleMapper.findAll();
//            Optional<Role> any = roleList.stream().filter(role -> "dz001".equals(role.getSn())).findAny();
//            any.ifPresent(role->{
//                roleMapper.addMiddle(emp.getId(), Collections.singletonList(role.getId()));
//            });
//        }else {
//            // todo 否则就是添加正常平台员工
        emp.setLogininfoId(logininfo.getId());
        super.add(emp);
//            // 角色
        roleMapper.addMiddle(emp.getId(), emp.getRoles());
//        }


    }

    @Override
    public void update(Employee emp) {
        super.update(emp);
        // 删除
        roleMapper.deleteByEmpId(emp.getId());
        // 角色
        roleMapper.addMiddle(emp.getId(), emp.getRoles());
    }

    @Override
    public PageList<Employee> queryByPage(BaseQuery query) {
        PageList<Employee> pageList = super.queryByPage(query);
        if (null == pageList || CollectionUtils.isEmpty(pageList.getRows())) {
            return pageList;
        }
        // 将角色集合放入到每个人的对象下面
        List<Employee> emps = pageList.getRows();
        List<Long> empIds = emps.stream().map(Employee::getId).collect(Collectors.toList());
        // 根据empIds集合获取到所有的角色
        List<EmpAndRoleVo> empAndRoleList =  roleMapper.findByEmpIds(empIds);
        // 将 empAndRoleList 转成 map key：empid  value：List<Long> roleId
        Map<Long, List<Long>> map = empAndRoleList.stream().collect(Collectors.groupingBy(EmpAndRoleVo::getEmployeeId
                , Collectors.mapping(EmpAndRoleVo::getRoleId, Collectors.toList())));
        //遍历emps 将roleId集合放入到emp对象中
        emps.forEach(emp->{
            List<Long> roleIds = map.get(emp.getId());
            emp.setRoles(roleIds);
        });
        return pageList;
    }


    @Override
    public List<Employee> findEmpByDeptId(Long id) {

        return employeeMapper.findEmpByDeptId(id);
    }


}
